<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>
    <div class="box" id="box1">box1</div>
    <div class="box" id="box2">box2</div>
    <script>
        // 高内聚，低耦合
        // 构造函数+原型
        //使用构造函数来写
        function Drag (selecter) {
            this.box = document.querySelector(selecter)
            this.binEevents ()
        }
        Object.assign //对象合并，这样可以较方便的给Drag.prototype加方法
        Object.assign(Drag.prototype, {
            //binEevents给事件绑方法
            binEevents () {
                this.box.onmousedown = e => {
                    // 记录鼠标到box边缘的坐标
                    let disX = e.offsetX,
                        disY = e.offsetY
                    document.onmousemove = e => {
                        let left = e.clientX - disX,
                            top = e.clientY - disY
                            this.move(left, top)
                    }
                    document.onmouseup = function () {
                        this.onmousemove = null
                    }
                    return false
                }
            },
            move (left, top) {
                this.box.style.left = left + 'px'
                this.box.style.top = top + 'px'
            }
        })
        new Drag('#box1')
        new Drag('#box2')
    </script>
</body>
</html>